/**
 * Copyright (C) 2009-2012, KingHool.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses.
 */
package com.kinghool.smodel.io.xml;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.kinghool.ebos.commons.utils.Utils;
import com.kinghool.smodel.io.IModelChannel;

/**
 * 
 * @Author Allen Deng(dengtailin@gmail.com) 
 */
public class XmlStringChannel extends XmlChannel implements IModelChannel {
    private String xml;
	 
	public XmlStringChannel() {
		this(null);
	}
  
	public XmlStringChannel(String xml) {
		this.xml = xml;
	}
   
	protected IDocumentProvider getDocumentProvider() {
		return new IDocumentProvider() {
			public Document getDocument() throws FileNotFoundException, JDOMException, IOException {
				return new SAXBuilder().build(new StringReader(Utils.getNotNullString(xml)));
			}
		};
	}
	
	protected Writer getWriter() {
		return new StringWriter();
	}

	protected void afterLoad(Writer writer) {
		xml = ((StringWriter)writer).getBuffer().toString();
		super.afterLoad(writer);
	}
	
	public String getMappedObject() {
		return xml;
	} 
	 
	public void setMappedObject(Object xml) {
		this.xml = (xml == null ? null : String.valueOf(xml));
	}

}
